import { useState, useCallback } from "react";
import styles from "./AddWarehouse.module.css";

interface Product {
    id: number;
    sku: string;
    productName: string;
    inboundPrice: number;
    quantity: number;
}

interface FormData {
    team: string;
    warehouseName: string;
    inboundType: string;
    volume: string;
    departureTime: string;
    arrivalTime: string;
    estimatedTime: string;
    referenceNumber: string;
    remarks: string;
    services: { [key: string]: number };
}

const AddWarehouse = () => {
    const [formData, setFormData] = useState<FormData>({
        team: "深圳物流达12c",
        warehouseName: "东京日韩里仓库",
        inboundType: "",
        volume: "",
        departureTime: "",
        arrivalTime: "",
        estimatedTime: "",
        referenceNumber: "",
        remarks: "",
        services: {}
    });

    const [products, setProducts] = useState<Product[]>([]);
    const [skuInput, setSkuInput] = useState("");
    const [loading, setLoading] = useState(false);

    const handleInputChange = useCallback((e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
        const { name, value } = e.target;
        setFormData(prev => ({
            ...prev,
            [name]: value
        }));
    }, []);

    const toggleService = useCallback((service: string) => {
        setFormData(prev => {
            const newServices = { ...prev.services };
            if (service in newServices) {
                delete newServices[service];
            } else {
                newServices[service] = 1;
            }
            return { ...prev, services: newServices };
        });
    }, []);

    const handleServiceQuantityChange = useCallback((service: string, quantity: string) => {
        const numericQuantity = parseInt(quantity) || 0;
        setFormData(prev => ({
            ...prev,
            services: {
                ...prev.services,
                [service]: numericQuantity
            }
        }));
    }, []);

    const addProduct = useCallback(() => {
        const newProduct: Product = {
            id: Date.now(),
            sku: "",
            productName: "",
            inboundPrice: 0,
            quantity: 1
        };
        setProducts(prev => [...prev, newProduct]);
    }, []);

    const handleProductChange = useCallback((index: number, field: keyof Product, value: string | number) => {
        setProducts(prev => {
            const newProducts = [...prev];
            newProducts[index] = { ...newProducts[index], [field]: value };
            return newProducts;
        });
    }, []);

    const removeProduct = useCallback((id: number) => {
        setProducts(prev => prev.filter(p => p.id !== id));
    }, []);

    const handleSkuKeyPress = useCallback((e: React.KeyboardEvent<HTMLInputElement>) => {
        if (e.key === 'Enter' && skuInput.trim()) {
            const newProduct: Product = {
                id: Date.now(),
                sku: skuInput.trim(),
                productName: "",
                inboundPrice: 0,
                quantity: 1
            };
            setProducts(prev => [...prev, newProduct]);
            setSkuInput("");
        }
    }, [skuInput]);

    const validateForm = useCallback(() => {
        if (!formData.team || !formData.warehouseName || !formData.inboundType || !formData.estimatedTime) {
            alert("请填写所有必填字段");
            return false;
        }
        
        for (const product of products) {
            if (!product.sku || product.inboundPrice <= 0 || product.quantity <= 0) {
                alert("请完善产品信息（SKU、入库价和数量不能为空或小于等于0）");
                return false;
            }
        }
        
        return true;
    }, [formData, products]);

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        
        if (!validateForm()) {
            return;
        }

        setLoading(true);
        try {
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 1000));
            
            console.log("表单数据:", formData);
            console.log("产品数据:", products);
            alert("创建入库单成功！");
            
            // 重置表单
            setFormData({
                team: "深圳物流达12c",
                warehouseName: "东京日韩里仓库",
                inboundType: "",
                volume: "",
                departureTime: "",
                arrivalTime: "",
                estimatedTime: "",
                referenceNumber: "",
                remarks: "",
                services: {}
            });
            setProducts([]);
            setSkuInput("");
        } catch {
            alert("创建失败，请重试");
        } finally {
            setLoading(false);
        }
    };

    const handleBatchImport = useCallback(() => {
        // 模拟批量导入功能
        alert("批量导入功能开发中...");
    }, []);

    const handleDownloadTemplate = useCallback(() => {
        // 模拟下载模板功能
        alert("正在下载模板...");
    }, []);

    return (
        <div className={styles.container}>
            <form onSubmit={handleSubmit}>
                <div className={styles.formRow}>
                    <div className={styles.formGroup}>
                        <label className={`${styles.formLabel} ${styles.required}`}>团队</label>
                        <select
                            name="team"
                            value={formData.team}
                            onChange={handleInputChange}
                            className={styles.formSelect}
                            required
                            disabled={loading}
                        >
                            <option value="深圳物流达12c">深圳物流达12c</option>
                        </select>
                    </div>
                    <div className={styles.formGroup}>
                        <label className={`${styles.formLabel} ${styles.required}`}>仓库名称</label>
                        <select
                            name="warehouseName"
                            value={formData.warehouseName}
                            onChange={handleInputChange}
                            className={styles.formSelect}
                            required
                            disabled={loading}
                        >
                            <option value="东京日韩里仓库">东京日韩里仓库</option>
                        </select>
                    </div>
                    <div className={styles.formGroup}>
                        <label className={`${styles.formLabel} ${styles.required}`}>入库类型</label>
                        <select
                            name="inboundType"
                            value={formData.inboundType}
                            onChange={handleInputChange}
                            className={styles.formSelect}
                            required
                            disabled={loading}
                        >
                            <option value="">请选择入库类型</option>
                            <option value="普通入库">普通入库</option>
                            <option value="紧急入库">紧急入库</option>
                        </select>
                    </div>
                </div>

                <div className={styles.formRow}>
                    <div className={styles.formGroup}>
                        <label className={styles.formLabel}>体积(m³)</label>
                        <input
                            type="text"
                            name="volume"
                            value={formData.volume}
                            onChange={handleInputChange}
                            className={styles.formInput}
                            placeholder="选填"
                            disabled={loading}
                        />
                    </div>
                    <div className={styles.formGroup}>
                        <label className={styles.formLabel}>离港时间</label>
                        <input
                            type="datetime-local"
                            name="departureTime"
                            value={formData.departureTime}
                            onChange={handleInputChange}
                            className={styles.formInput}
                            disabled={loading}
                        />
                    </div>
                    <div className={styles.formGroup}>
                        <label className={styles.formLabel}>到港时间</label>
                        <input
                            type="datetime-local"
                            name="arrivalTime"
                            value={formData.arrivalTime}
                            onChange={handleInputChange}
                            className={styles.formInput}
                            disabled={loading}
                        />
                    </div>
                </div>

                <div className={styles.formRow}>
                    <div className={styles.formGroup}>
                        <label className={`${styles.formLabel} ${styles.required}`}>预计到仓时间</label>
                        <input
                            type="datetime-local"
                            name="estimatedTime"
                            value={formData.estimatedTime}
                            onChange={handleInputChange}
                            className={styles.formInput}
                            required
                            disabled={loading}
                        />
                    </div>
                    <div className={styles.formGroup}>
                        <label className={styles.formLabel}>参考号</label>
                        <input
                            type="text"
                            name="referenceNumber"
                            value={formData.referenceNumber}
                            onChange={handleInputChange}
                            className={styles.formInput}
                            placeholder="选填"
                            disabled={loading}
                        />
                    </div>
                </div>

                

                <div className={styles.divider} />
                <div className={styles.sectionTitle}>货物信息</div>

                <div className={styles.cargoInfo}>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                            <input
                                type="text"
                                className={styles.skuInput}
                                placeholder="请通过扫描或输入产品SKU回车"
                                value={skuInput}
                                onChange={(e) => setSkuInput(e.target.value)}
                                onKeyPress={handleSkuKeyPress}
                                disabled={loading}
                            />
                            <button type="button" className={styles.primaryButton} onClick={handleBatchImport} disabled={loading}>
                                批量导入
                            </button>
                            <button type="button" className={styles.secondaryButton} onClick={handleDownloadTemplate} disabled={loading}>
                                下载模板
                            </button>
                        </div>
                        <button type="button" className={styles.addButton} onClick={addProduct} disabled={loading}>
                            添加产品
                        </button>
                    </div>

                    <table className={styles.table}>
                        <thead>
                            <tr>
                                <th>箱号</th>
                                <th className={styles.required}>SKU</th>
                                <th>产品名称</th>
                                <th className={styles.required}>入库价(円)</th>
                                <th className={styles.required}>数量</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody style={{ position: 'relative' }}>
                            <tr style={{ position: 'absolute', width: '100%', textAlign: 'center', top: '50%', transform: 'translateY(-50%)' }}>
                                <td colSpan={6}>货物信息</td>
                            </tr>
                            {products.map((product, index) => (
                                <tr key={product.id}>
                                    <td>{index + 1}</td>
                                    <td>
                                        <input
                                            type="text"
                                            value={product.sku}
                                            onChange={(e) => handleProductChange(index, 'sku', e.target.value)}
                                            disabled={loading}
                                        />
                                    </td>
                                    <td>
                                        <input
                                            type="text"
                                            value={product.productName}
                                            onChange={(e) => handleProductChange(index, 'productName', e.target.value)}
                                            disabled={loading}
                                        />
                                    </td>
                                    <td>
                                        <input
                                            type="number"
                                            value={product.inboundPrice}
                                            onChange={(e) => handleProductChange(index, 'inboundPrice', Number(e.target.value))}
                                            min="0"
                                            step="0.01"
                                            disabled={loading}
                                        />
                                    </td>
                                    <td>
                                        <input
                                            type="number"
                                            value={product.quantity}
                                            onChange={(e) => handleProductChange(index, 'quantity', Number(e.target.value))}
                                            min="1"
                                            disabled={loading}
                                        />
                                    </td>
                                    <td>
                                        <button
                                            type="button"
                                            onClick={() => removeProduct(product.id)}
                                            className={styles.deleteButton}
                                            disabled={loading}
                                        >
                                            删除
                                        </button>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>

                <div className={styles.divider} />

                <div className={styles.formRow}>
                    <div className={styles.formGroup}>
                        <label className={styles.formLabel}>增值服务</label>
                        <div className={styles.checkboxGroup}>
                            <div className={styles.checkboxRow}>
                                {[
                                    "100*100*80(箱子)",
                                    "12()",
                                    "999()",
                                    "测试(222)"
                                ].map(service => (
                                    <div key={service} className={styles.checkboxItem}>
                                        <input
                                            type="checkbox"
                                            checked={service in formData.services}
                                            onChange={() => toggleService(service)}
                                            className={styles.checkboxInput}
                                            disabled={loading}
                                        />
                                        <label>{service}</label>
                                        {service in formData.services && (
                                            <input
                                                type="number"
                                                value={formData.services[service]}
                                                onChange={(e) => handleServiceQuantityChange(service, e.target.value)}
                                                className={styles.quantityInput}
                                                min="1"
                                                disabled={loading}
                                            />
                                        )}
                                    </div>
                                ))}
                            </div>
                            <div className={styles.checkboxRow}>
                                {[
                                    "拍照()",
                                    "箱子61*42*35尺寸()",
                                    "cs1(999)"
                                ].map(service => (
                                    <div key={service} className={styles.checkboxItem}>
                                        <input
                                            type="checkbox"
                                            checked={service in formData.services}
                                            onChange={() => toggleService(service)}
                                            className={styles.checkboxInput}
                                            disabled={loading}
                                        />
                                        <label>{service}</label>
                                        {service in formData.services && (
                                            <input
                                                type="number"
                                                value={formData.services[service]}
                                                onChange={(e) => handleServiceQuantityChange(service, e.target.value)}
                                                className={styles.quantityInput}
                                                min="1"
                                                disabled={loading}
                                            />
                                        )}
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>
                </div>


                <button type="submit" className={styles.submitButton} disabled={loading}>
                    {loading ? "创建中..." : "创建入库单"}
                </button>
            </form>
        </div>
    );
};

export default AddWarehouse;